package dmsxl.haxibiao;

import java.lang.reflect.Array;
import java.util.*;

/**
 * Author: Zhang Dongwei
 * Date: 2023/4/14 22:25
 * 编写一个算法来判断一个数 n 是不是快乐数。
 */
public class hxb4_202 {

    public static void main(String[] args) {
        System.out.println(isHappy(19));
    }

//    自己写的，效率很低
    public static boolean isHappy1(int n) {
        Set<Object> set = new HashSet<>();
        while (true){
            String s = n + "";
            int count = 0;
            for (int i = 0; i < s.length(); i++){
                count += (s.charAt(i)-'0')*(s.charAt(i)-'0');
            }
            if (set.contains(count)) return false;
            else set.add(count);
            if (count == 1) return true;
            n = count;
            System.out.println(count);
            System.out.println(set);
        }
    }

    public static boolean isHappy(int n) {
        Set<Integer> record = new HashSet<>();
        while (n != 1 && !record.contains(n)) {
            record.add(n);
            n = getNextNumber(n);
            System.out.println(n);
        }
        return n == 1;
    }

    public static int getNextNumber(int n) {
        int res = 0;
        while (n > 0) {
            int temp = n % 10;
            res += temp * temp;
            n = n / 10;
        }
        return res;
    }
}
